package net.lab1024.sa.base.module.support.job.sample;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.base.common.util.RedisUtil;
import net.lab1024.sa.base.common.util.RestTemplateUtil;
import net.lab1024.sa.base.common.util.SmartDateFormatterEnum;
import net.lab1024.sa.base.common.util.SmartLocalDateUtil;
import net.lab1024.sa.base.module.support.config.TemplatelogJobDao;
import net.lab1024.sa.base.module.support.config.UserJobDao;
import net.lab1024.sa.base.module.support.config.domain.*;
import net.lab1024.sa.base.module.support.job.core.SmartJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SmartJobSendUserWx implements SmartJob {

    @Autowired
    private RestTemplateUtil restTemplateUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserJobDao userJobDao;

    @Autowired
    private TemplatelogJobDao templatelogJobDao;

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public String run(String param) {
        List<UserVO> userList = userJobDao.queryUserMessage();
        String name = "";
        if(userList.size()>0){
            for (UserVO item:userList){
                if(item.getUsername().length()==28){
                    TemplatelogQueryForm queryForm = new TemplatelogQueryForm();
                    queryForm.setIsOk("1");
                    queryForm.setSendType("2");
                    queryForm.setSendId(item.getUserId());
                    TemplatelogEntity templatelog = templatelogJobDao.selectOneByPamars(queryForm);
                    if(templatelog==null){
                        name+=item.getNickName()+",";
                        sendTemplateMessage(item);
                    }
                }
            }
        }

        return "本次发送"+name;
    }

    public Boolean sendTemplateMessage(UserVO item) {
        HashMap<String, String> temMap =  new HashMap<>();
        String dqtime = SmartLocalDateUtil.format(LocalDateTime.now(), SmartDateFormatterEnum.YMD_HMS);
        String openid = item.getUsername();
        Integer msgCount = item.getMsgCount();
        temMap.put("time2", dqtime);
        temMap.put("short_thing3","未读提醒");
        temMap.put("character_string1",msgCount+"");

        TemplateMessageVo programTemplateMessageVo = new TemplateMessageVo();
        programTemplateMessageVo.setTemplate_id("hOeGsduunDuB2DyiCMP8dfuurjkBEpMMHZMqNqFZvmU");

        //组装关键字数据
        HashMap<String, SendTemplateMessageItemVo> hashMap = new HashMap<>();
        temMap.forEach((key, value) -> hashMap.put(key, new SendTemplateMessageItemVo(value)));
        programTemplateMessageVo.setPage("pages/index/index?familyId=5");
        programTemplateMessageVo.setData(hashMap);
        programTemplateMessageVo.setTouser(openid);
        TemplatelogEntity templatelog = new TemplatelogEntity();
        templatelog.setAddtime(LocalDateTime.now());
        templatelog.setSendId(item.getUserId());
        templatelog.setSendName(item.getNickName());
        templatelog.setSendType("2");
        templatelog.setTemplateId("hOeGsduunDuB2DyiCMP8dfuurjkBEpMMHZMqNqFZvmU");
        templatelog.setContent(temMap.toString());
        templatelog.setSendOpenid(openid);
        templatelog.setUnreadCount(msgCount+"");
        return sendMiniSubscribeMessage(programTemplateMessageVo,templatelog);
    }

    public  Boolean sendMiniSubscribeMessage(TemplateMessageVo templateMessage,TemplatelogEntity templatelog) {
        String accessToken = getMiniAccessToken();
        String url = StrUtil.format("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={}", accessToken);
        JSONObject messAge = JSONObject.parseObject(JSONObject.toJSONString(templateMessage));
        String result = restTemplateUtil.postJsonData(url, messAge);
        JSONObject data = JSONObject.parseObject(result);
        templatelog.setIsOk("1");
        if (ObjectUtil.isNull(data)) {
//            throw new CrmebException("微信平台接口异常，没任何数据返回！");
        }
        if (data.containsKey("errcode") && !"0".equals(data.getString("errcode"))) {
            if ("40001".equals(data.getString("errcode"))) {
//                wxExceptionDispose(data, "微信小程序发送订阅消息异常");
                redisUtil.delete("wechat_mini_accessToken");
                accessToken = getMiniAccessToken();
                url = StrUtil.format("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={}", accessToken);
                result = restTemplateUtil.postJsonData(url, messAge);
                JSONObject data2 = JSONObject.parseObject(result);
                if (data2.containsKey("errcode") && !"0".equals(data2.getString("errcode"))) {
                    if (data2.containsKey("errmsg")) {
                        System.out.println("1"+data2);
                        templatelog.setIsOk("2");
                        templatelog.setReturnContent(result);
//                        wxExceptionDispose(data2, "微信小程序发送订阅消息重试异常");
//                        throw new CrmebException("微信接口调用失败：" + data2.getString("errcode") + data2.getString("errmsg"));
                    }
                } else {
                    templatelog.setReturnContent(result);
                    templatelogJobDao.insert(templatelog);
                    return Boolean.TRUE;
                }
            }
            if (data.containsKey("errmsg")) {
                System.out.println("1"+data);
                templatelog.setIsOk("2");
                templatelog.setReturnContent(result);
//                wxExceptionDispose(data, "微信小程序发送订阅消息异常");
//                throw new CrmebException("微信接口调用失败：" + data.getString("errcode") + data.getString("errmsg"));
            }

        }
        templatelogJobDao.insert(templatelog);
        return Boolean.TRUE;
    }

    public String getMiniAccessToken() {
        boolean exists = redisUtil.exists("wechat_mini_accessToken");
        if (exists) {
            Object accessToken = redisUtil.get("wechat_mini_accessToken");
            return accessToken.toString();
        }
        String appId = "wxe473a31fd17b48c4";
//        if (StrUtil.isBlank(appId)) {
//            throw new CrmebException("微信小程序appId未设置");
//        }
        String secret = "3d6997955c4b1a7285aef8f729bfbc3a";
//        if (StrUtil.isBlank(secret)) {
//            throw new CrmebException("微信小程序secret未设置");
//        }
        WeChatAccessTokenVo accessTokenVo = getAccessToken(appId, secret, "mini");
        // 缓存accessToken
        redisUtil.set("wechat_mini_accessToken", accessTokenVo.getAccessToken(),
                accessTokenVo.getExpiresIn().longValue() - 1800L, TimeUnit.SECONDS);
        return accessTokenVo.getAccessToken();
    }

    private WeChatAccessTokenVo getAccessToken(String appId, String secret, String type) {
        String url = StrUtil.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}", appId, secret);
        JSONObject data = restTemplateUtil.getData(url);
        if (ObjectUtil.isNull(data)) {
//            throw new CrmebException("微信平台接口异常，没任何数据返回！");
        }
        if (data.containsKey("errcode") && !"0".equals(data.getString("errcode"))) {
            if (data.containsKey("errmsg")) {
                System.out.println("微信接口调用失败：" + data.getString("errcode") + data.getString("errmsg"));
                // 保存到微信异常表
//                wxExceptionDispose(data, StrUtil.format("微信获取accessToken异常，{}端", type));
//                throw new CrmebException("微信接口调用失败：" + data.getString("errcode") + data.getString("errmsg"));
            }
        }
        return JSONObject.parseObject(data.toJSONString(), WeChatAccessTokenVo.class);
    }
}
